package com.zhr.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import com.zhr.common.ResultData;
import com.zhr.common.ResultState;
import com.zhr.tools.code3.entityParameter.AesInfo;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author ZHR
 */
@RestController
public class AesController {
    /**
     * 加密
     */
    private static final int TYPE_ENCRYPT = 1;
    /**
     * 解密
     */
    private static final int TYPE_DECRYPT = 2;

    /**
     * AES加解密
     * <p>
     * aesInfo.getKey     秘钥
     * aesInfo.getType()    1 加密 2 解密
     * aesInfo.getContent() 待加解密内容
     *
     * @return 加解密结果
     */
    @PostMapping("aes")
    public ResultData<String> sendRequest(
            @RequestBody AesInfo aesInfo) {
        try {
            AES aesSecurity = SecureUtil.aes(aesInfo.getKey().getBytes());
            if (aesInfo.getType() == TYPE_ENCRYPT) {
                return new ResultData<>(aesSecurity.encryptBase64(aesInfo.getContent()));
            } else if (aesInfo.getType() == TYPE_DECRYPT) {
                return new ResultData<>(aesSecurity.decryptStr(aesInfo.getContent()));
            } else {
                return new ResultData<>(ResultState.BIZ_FAIL, "请输入正确操作类型");
            }
        } catch (Exception e) {
            return new ResultData<>(e.getMessage() + "\n");
        }
    }

    public static void main(String[] args) {
        AES aesSecurity = SecureUtil.aes("12345678asdfghjk12345678asdfghjk12345678asdfghjk12345678asdfghjk12345678asdfghjk12345678asdfghjk12345678asdfghjk12345678asdfghjk".getBytes());
        String s =  aesSecurity.encryptBase64("hello");
        System.out.println(s);
        byte[] decrypt = aesSecurity.decrypt(s);
        System.out.println(new String(decrypt));
    }
}
